package st.business.tepth.business.user.busnumber.workholder.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DiagnoseBean;
import st.business.tepth.business.bean.SearchDiagnoseBean;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.recycler.BaseDecoration;

/**
 * @author zhangyu
 * @date 2019/2/14
 */
public class DialogSearchTrouble extends Dialog {
    private Disposable mDisposable;

    public DialogSearchTrouble(@NonNull Context context,
                               final int repairId,
                               final int repair_task_id,
                               final int repair_phenomenon_id,
                               final String token, final OnItemChooseListener<DiagnoseBean> listener) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(context).
                inflate(R.layout.dialog_search_trouble, null);

        final EditText editText = view.findViewById(R.id.et_search_trouble);
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        view.findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                if (listener != null && !name.isEmpty()) {
                    DiagnoseBean diagnoseBean = new DiagnoseBean();
                    diagnoseBean.setRepair_id(repairId);
                    diagnoseBean.setRepair_task_id(repair_task_id);
                    diagnoseBean.setRepair_phenomenon_id(repair_phenomenon_id);
                    diagnoseBean.setName(name);
                    diagnoseBean.setType(1);
                    diagnoseBean.setTemp(true);
                    diagnoseBean.setManual(true);
                    listener.onChoose(diagnoseBean);
                    dismiss();
                }
            }
        });
        SpannableString spPassword = new SpannableString(context.getResources()
                .getString(R.string._search_trouble_info));//定义hint的值
        AbsoluteSizeSpan spSizePassword = new AbsoluteSizeSpan(10, true);//设置字体大小 true表示单位是sp
        spPassword.setSpan(spSizePassword, 0, spPassword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(spPassword));

        final RecyclerView recyclerView = view.findViewById(R.id.recycler_view_trouble);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                DiagnoseBean diagnoseBean = (DiagnoseBean) adapter.getItem(position);
                if (diagnoseBean != null) {
                    diagnoseBean.setRepair_id(repairId);
                    diagnoseBean.setReference_id(diagnoseBean.getId());
                    diagnoseBean.setRepair_task_id(repair_task_id);
                    diagnoseBean.setRepair_phenomenon_id(repair_phenomenon_id);
                    diagnoseBean.setManual(false);
                    diagnoseBean.setTemp(true);
                    diagnoseBean.setType(0);
                    if (listener != null) {
                        listener.onChoose(diagnoseBean);
                    }
                }
                dismiss();
            }
        });
        Observer observable = RxTextView.textChanges(editText)
                .subscribeOn(AndroidSchedulers.mainThread())
                .debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(CharSequence charSequence) throws Exception {
                        //清空adapter
//                        recyclerView.setVisibility(charSequence.length() > 0 ? View.VISIBLE :
//                                View.GONE);
                        return charSequence.length() > 0;
                    }
                })
                .switchMap(new Function<CharSequence, Observable<String>>() {
                    @Override
                    public Observable<String> apply(CharSequence charSequence) throws Exception {
                        return RxRestClient.builder()
                                .url(Url.SearchDiagnoseBean)
                                .params("faultPhenomenonId", repair_phenomenon_id)
                                .params("token", token)
                                .params("pageNumber", 1)
                                .params("pageSize", 50)
                                .params("name", charSequence.toString())
                                .build()
                                .onlyPost();
                    }
                })
                .subscribeWith(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        SearchDiagnoseBean searchBean =
                                new ObjConverter<SearchDiagnoseBean>().convert(object
                                        , new TypeReference<SearchDiagnoseBean>() {
                                        });
                        recyclerView.setAdapter(new TroubleAdapter(R.layout.item_search_trouble,
                                searchBean == null ? null : searchBean.getList()));
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        setContentView(view);
    }

    @Override
    public void dismiss() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    private class TroubleAdapter extends BaseQuickAdapter<DiagnoseBean, BaseViewHolder> {

        public TroubleAdapter(int layoutResId, @Nullable List<DiagnoseBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DiagnoseBean item) {
            helper.setText(R.id.tv_apply_time, item.getName());
        }
    }

    public void adjustSize() {
        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(); // 宽度
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度
            dialogWindow.setGravity(Gravity.TOP);
            dialogWindow.setAttributes(lp);
            show();
        }
    }
}
